package com.wiseasy.smartpos.cashierdemo.speech;

import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.widget.Toast;

import java.util.Locale;


public class SystemTTS extends UtteranceProgressListener implements TTS{
    private Context mContext;
    private static SystemTTS singleton;
    private TextToSpeech textToSpeech;
    private boolean isSuccess = true;

    public static SystemTTS getInstance(Context context) {
        if (singleton == null) {
            synchronized (SystemTTS.class) {
                if (singleton == null) {
                    singleton = new SystemTTS(context);
                }
            }
        }
        return singleton;
    }

    private SystemTTS(Context context) {
        this.mContext = context.getApplicationContext();
        textToSpeech = new TextToSpeech(mContext, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {

                if (i == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.US);
                    // Set the pitch, the higher the value, the higher the voice (for girls), the lower the value, the male voice,1.0 is the norm
                    textToSpeech.setPitch(1f);
                    textToSpeech.setSpeechRate(0.8f);
                    textToSpeech.setOnUtteranceProgressListener(SystemTTS.this);
                    if (result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED) {

                        isSuccess = false;
                    }
                }
            }
        });
    }

    public void playText(String playText) {
        if (!isSuccess) {
            Toast.makeText(mContext, "system do not support this language", Toast.LENGTH_SHORT).show();
            return;
        }
        if (textToSpeech != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                textToSpeech.speak(playText,
                        TextToSpeech.QUEUE_ADD, null, null);
            }
        }
    }

    @Override
    public void stopSpeak() {
        if (textToSpeech != null) {
            textToSpeech.stop();
        }
    }

    public void shutdown() {
        if (textToSpeech != null) {
            textToSpeech.shutdown();
            singleton = null;
            textToSpeech = null;
        }
    }



    @Override
    public void onStart(String utteranceId) {

    }

    @Override
    public void onDone(String utteranceId) {
    }

    @Override
    public void onError(String utteranceId) {

    }

}
